package com.deyang.tool;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;


import com.deyang.application.MyApplication;
import com.deyang.callback.ValueCallBack;
import com.deyang.config.IntentConfig;
import com.deyang.entity.BaseResponse;
import com.deyang.service.IHttpService;
import com.deyang.ui.activity.LoginActivity;
import com.deyang.util.JsonUtil;
import com.deyang.util.Logger;
import com.deyang.util.ToastUtil;

import java.net.ConnectException;
import java.util.Map;

import javax.net.ssl.SSLHandshakeException;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.adapter.rxjava.HttpException;
import rx.Observer;
import rx.Subscriber;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class HttpTool {

    private static final String TAG = "HttpTool";

    /**
     * 将map 转换为 RequestBody
     *
     * @param map
     * @return
     */
    public static RequestBody mapToRequestBody(Map map) {
        String indexReqJson = JsonUtil.map2Json(map);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), indexReqJson);
        return body;
    }

    /**
     * 登录 创建 观察者  回调
     *
     * @return
     */
    public static Subscriber<String> getLoginTokenSubscriber(final Dialog loadingDialog, final ValueCallBack callBack) {
        return new Subscriber<String>() {
            @Override
            public void onCompleted() {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                Logger.e(TAG, "错误返回:" + e.getMessage());
                if (e instanceof HttpException) {
                    //获取对应statusCode和Message
                    HttpException exception = (HttpException) e;
                    int code = exception.response().code();
                    if (code == 404) {
                        ToastUtil.showError("登录失败，请检查用户名和密码！");
                    } else {
                        ToastUtil.showError("服务器请求失败！");
                    }
                    callBack.onFail(e.getMessage());
                } else if (e instanceof SSLHandshakeException) {
                    //接下来就是各种异常类型判断...
                    callBack.onFail(e.getMessage());
                    ToastUtil.showError("服务器请求失败！");
                } else if (e instanceof ConnectException) {
                    //接下来就是各种异常类型判断...
                    callBack.onFail(e.getMessage());
                    ToastUtil.showError("请检查当前网络！");
                } else {
                    callBack.onFail(e.getMessage());
                    ToastUtil.showError("服务器请求失败！");
                }
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
            }

            @Override
            public void onNext(String token) {
                callBack.onSuccess(token);
            }
        };

    }


    /**
     * 返回baseResponse 创建 观察者  回调
     *
     * @param activity
     * @param loadingDialog
     * @param callBack
     * @return
     */
    public static Subscriber<BaseResponse> getBaseResponseSubscriber(final Activity activity,
                                                                     final Dialog loadingDialog,
                                                                     final ValueCallBack callBack) {
        return new Subscriber<BaseResponse>() {
            @Override
            public void onCompleted() {
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
            }

            @Override
            public void onError(Throwable e) {
                Logger.e(TAG, "错误返回:" + e.getMessage());
                if (e instanceof HttpException) {
                    //获取对应statusCode和Message
                    HttpException exception = (HttpException) e;
                    int code = exception.response().code();
                    Logger.e(TAG, "错误返回：code:" + code);
                    if (code == 401) {
                        MyApplication application = MyApplication.getApplication();
                        application.finishAllActivity();
                        Intent intent = new Intent(application, LoginActivity.class);
                        intent.putExtra(IntentConfig.TokenInvalid, true);
                        activity.startActivity(intent);
                    } else {
                        ToastUtil.showError("服务器请求失败！");
                    }
                    callBack.onFail(e.getMessage());
                } else if (e instanceof SSLHandshakeException) {
                    //接下来就是各种异常类型判断...
                    callBack.onFail(e.getMessage());
                    ToastUtil.showError("服务器请求失败！");
                } else if (e instanceof ConnectException) {
                    //接下来就是各种异常类型判断...
                    callBack.onFail(e.getMessage());
                    ToastUtil.showError("请检查当前网络！");
                } else {
                    callBack.onFail(e.getMessage());
                    ToastUtil.showError("服务器请求失败！");
                }
                if (loadingDialog != null) {
                    loadingDialog.dismiss();
                }
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                callBack.onSuccess(baseResponse);
            }
        };

    }


}
